package com.lauor.smpedr.spring.session;

import com.lauor.smpedr.Configuration;
import com.lauor.smpedr.core.SqlGenerator;
import com.lauor.smpedr.core.handler.provider.DefaultResultSetHandler;
import com.lauor.smpedr.core.handler.ResultSetHandler;
import com.lauor.smpedr.session.SqlSession;
import com.lauor.smpedr.session.SqlSessionFactory;
import com.lauor.smpedr.session.provider.DefaultSqlSessionFactory;
import com.lauor.smpedr.transaction.TransactionIsolationLevel;

import java.lang.reflect.Proxy;

/**
 * spring sqlSession工厂
 */
public class SpringManagedSqlSessionFactory implements SqlSessionFactory {
    private Configuration configuration;

    private SqlGenerator sqlGenerator;

    private ResultSetHandler resultSetHandler;

    public SpringManagedSqlSessionFactory(Configuration configuration, SqlGenerator sqlGenerator, ResultSetHandler resultSetHandler) {
        this.configuration = configuration;
        this.sqlGenerator = sqlGenerator;
        this.resultSetHandler = resultSetHandler;
    }

    public SpringManagedSqlSessionFactory(Configuration configuration, SqlGenerator sqlGenerator) {
        this(configuration, sqlGenerator, new DefaultResultSetHandler(configuration));
    }

    @Override
    public SqlSession openSession() {
        SqlSessionFactory defaultSqlSessionFactory = new DefaultSqlSessionFactory(this.configuration, this.sqlGenerator, this.resultSetHandler);
        //构建代理对象spring manage
        return (SqlSession) Proxy.newProxyInstance(SqlSession.class.getClassLoader(), new Class[]{SqlSession.class}, new SpringManagedSqlSessionProxy(defaultSqlSessionFactory));
    }

    @Override
    public SqlGenerator getSqlGenerator() {
        return this.sqlGenerator;
    }

    @Override
    public SqlSession openSession(boolean autoCommit) {
        throw new UnsupportedOperationException("openSession(boolean autoCommit) not support");
    }

    @Override
    public SqlSession openSession(TransactionIsolationLevel level) {
        throw new UnsupportedOperationException("openSession(TransactionIsolationLevel level) not support");
    }

    @Override
    public SqlSession openSession(TransactionIsolationLevel level, boolean autoCommit) {
        throw new UnsupportedOperationException("openSession(TransactionIsolationLevel level, boolean autoCommit) not support");
    }
}
